﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Threading.Tasks;
using MySQL.Db;

namespace Gollie.Ajax
{
	public class VendorLogin : AjaxResult
	{
		public string CookieExpiration;
		public uint CashierId;
		public string WebToken;

		public VendorLogin() : base(null) { }

		public VendorLogin(UserLoginArg arg) //string user, string password)
			: base(arg)
		{
		}

		protected override void Init(AjaxArg ajaxArg)
		{
			UserLoginArg arg = (UserLoginArg)ajaxArg;

			try
			{
				string wwHash = Hash.GetHash(arg.ww);

				ResultSet resultSet = Database.Queries.Login(arg.tokenUser, wwHash);

				if (resultSet.Count != 1)
				{
					this.ErrorCode = 4;
					throw new Exception("Gebruiker niet gevonden");
				}

				UserInfo userInfo = new UserInfo(resultSet);

				//user cannot be a regular customer
				if (false == (userInfo.Role == Role.SuperUser || userInfo.Role == Role.Administrator || userInfo.Role == Role.Sales || userInfo.Role == Role.Desk))
				{
					this.ErrorCode = 4;
					throw new Exception("Gebruiker niet gevonden");
				}

				this.CashierId = userInfo.Id;
				this.CookieExpiration = ConfigAppSettings.GetValue("CashierSessionExpirationMinutes");
				this.WebToken = userInfo.WebToken;
			}
			catch (Exception e)
			{
				if (this.ErrorCode == 0)
					this.ErrorCode = 99;

				this.ErrorMessage = e.Message;
			}
		}
	}
}